import React, { Component } from 'react'

const CanvasClock = React.createClass({
  componentDidMount() {
    const dom = document.getElementById('clock')
    this.ctx = dom.getContext('2d')
    const { width, height } = this.ctx.canvas
    this.r = width / 2
    this.drawBackground()
  },
  render() {
    return (
      <div className={`rt-CanvasClock-container`}>
        <canvas id="clock" width="200px" height="200px"></canvas>
      </div>
    )
  },
  handleClick() {
    const dom = document.getElementById('clock')
    this.ctx = dom.getContext('2d')
    const { width, height } = this.ctx.canvas
    this.r = width / 2
    this.drawBackground()
  },
  drawBackground() {
    this.ctx.translate(this.r, this.r)
    this.ctx.beginPath()
    this.ctx.lineWidth = 10
    this.ctx.arc(0, 0, this.r - 5, 0, Math.PI * 2)
    this.ctx.stroke()
    this.hourNumArr = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2]
    this.ctx.textAlign = 'center'
    this.ctx.textBaseline = 'middle'
    this.ctx.font = '18px Arial'
    this.hourNumArr.forEach((v, i) => {
      const rad = 2 * Math.PI / 12 * i
      const x = Math.cos(rad) * (this.r - 30)
      const y = Math.sin(rad) * (this.r - 30)
      this.ctx.fillText(v, x, y)
    })
    for (let i = 0; i < 60; i++) {
      const rad = 2 * Math.PI / 60 * i
      const x = Math.cos(rad) * (this.r - 18)
      const y = Math.sin(rad) * (this.r - 18)
      this.ctx.beginPath()
      if (i % 5 === 0) {
        this.ctx.fillStyle = 'red'
        this.ctx.arc(x, y, 2, 0, 2 * Math.PI)
      }
      else {
        this.ctx.fillStyle = '#000'
        this.ctx.arc(x, y, 2, 0, 2 * Math.PI)
      }
      this.ctx.fill()
    }
  }
})

export default CanvasClock